<template>
  <el-card>
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width:180px"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleCode">
        <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入权限字符"
            clearable
            size="small"
            style="width:180px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="可用状态"
            clearable
            size="small"
            style="width:180px"
        >
          <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width:180px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholde="开始日期"
            end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->

    <!-- 表格工具按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini"  @click="batchDelete">
          批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 表格工具按钮结束 -->
    <!-- 数据表格开始 -->
    <el-table border :data="roleTableList" @selection-change="selectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色ID" align="center" prop="roleId"/>
      <el-table-column label="角色名称" align="center" prop="roleName"/>
      <el-table-column label="权限编码" align="center" prop="roleCode"/>
      <el-table-column label="显示顺序" align="center" prop="roleSort"/>
      <el-table-column label="状态" prop="status" align="center" :formatter="statusFormatter"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200"/>
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button type="text" icon="el-icon-thumb" size="mini" @click="handleSelectMenu(scope.row)">
            分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 数据表格结束 -->
    <!-- 添加修改弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        center
        append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable size="small"/>
        </el-form-item>
        <el-form-item label="权限编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入权限字符" clearable size="small"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" clearable size="small"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
                :value="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable
                    size="small"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改弹出层结束 -->
    <!-- 分页控件开始 -->
    <el-pagination
        :current-page="queryParams.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryParams.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 分页控件结束 -->

    <!-- 分配权限弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="selectMenuOpen"
        width="400px"
        center
        append-to-body
    >
      <el-tree
          ref="menu"
          :data="menuOptions"
          show-checkbox
          node-key="menuId"
          highlight-current
          empty-text="加载中，请稍后"
          :props="{id:'menuId',children:'children',label:'menuName'}"
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectMenuSubmit">确 定</el-button>
        <el-button @click="cancelSelectMenu">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限和菜单弹出层结束 -->
  </el-card>
</template>

<script>

export default {
  // 定义页面数据
  data() {
    return {
      // 选中数组
      ids: [],
      roleId: undefined,
      // 非单个禁用
      single: true,
      // 选中的行
      selectedRows: [],
      // 被删除的数据
      roleIds:[],
      // 非多个禁用
      multiple: true,
      // 分页数据总条数
      total: 0,
      // 字典表格数据
      roleTableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        roleName: undefined,
        roleCode: undefined,
        status: undefined
      },
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        roleName: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ],
        roleCode: [
          {required: true, message: '权限编码不能为空', trigger: 'blur'}
        ]
      },
      // 是否打开分配权限的弹出层
      selectMenuOpen: false,
      // 菜单树的数据
      menuOptions: [],
      // 当前选中持角色ID
      currentRoleId: undefined
    }
  },

  created() {
    // 查询表格数据
    this.getRoleList()
    //加载状态的内容
    this.loadStatus();
  },
  methods: {
    selectionChange(val) {
      this.selectedRows = val;
      this.ids = val.map(item => item.roleId)
    },
    // 取消
    cancel() {
      this.open = false
      this.title = ''
      this.resetForm()
    },
    // 查询表格数据
    getRoleList() {
      this.$http.post("/system/role/listByPage", this.queryParams).then(resp => {
        this.roleTableList = resp.data.data.records;
        this.queryParams.total = resp.data.data.total;
      })
    },
    // 打开分配权限和菜单的弹出层
    handleSelectMenu(row) {
      this.currentRoleId = row.roleId || this.ids[0];
      this.title = '---分配权限---';
      this.selectMenuOpen = true;

      this.$http.get("/system/menu/listAllMenu").then(res => {
        const data = res.data.data;
        if (Array.isArray(data)) {
          this.menuOptions = this.handleTree(data, 'menuId');
        } else {
          console.error('Unexpected data format:', data);
          // Handle unexpected data format
          this.menuOptions = [];
        }
      });

      this.$http.get("/system/menu/selectMenusByRoleId/" + this.currentRoleId).then(res => {
        const data = res.data.data;
        if (Array.isArray(data)) {
          let menuids = [];
          for (const r of data) {
            if (r.menuType === "C") {
              menuids.push(r.menuId);
            }
          }

          if (this.$refs.menu) {
            this.$refs.menu.setCheckedKeys(menuids);
          }
        } else {
          // Handle unexpected data format
        }
      });
    },
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      rootId = rootId || 0
      // 对源数据进行深度克隆
      if (!Array.isArray(data)) return []
      const cloneData = JSON.parse(JSON.stringify(data)) || []
      // 循环所有的项目
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          return father[id] === child[parentId]
        })
        branchArr.length > 0 ? father.children = branchArr : ''
        // 返回上一层
        return father[parentId] === rootId
      })
      return treeData !== '' ? treeData : data
    },
    // 保存角色和菜单权限的关系
    handleSelectMenuSubmit() {
      // 获取选中的keys
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 获取半选的keys
      const halfCheckKeys = this.$refs.menu.getHalfCheckedKeys()
      // 组合成最后的keys
      const finalKey = halfCheckKeys.concat(checkedKeys)
      let url = `/system/menu/saveRoleMenu/${this.currentRoleId}`;
      if (finalKey && finalKey.length > 0) {
        url += `/${finalKey.join(',')}`;
      }
      this.$http.get(url)
          .then(res => {
        this.$message.success('分配成功')
        location.reload()
        this.selectMenuOpen = false
      }).catch(() => {
        this.selectMenuOpen = false
      })
    },
    // 关闭分配权限的弹出层
    cancelSelectMenu() {
      this.selectMenuOpen = false
      // this.menuOptions = []
    },
    // 批量删除
    batchDelete() {
      // 创建了一个包含所有选中行的roleId的新数组
      this.roleIds = this.selectedRows.map(item => item.roleId)
        this.$confirm("确认删除选中的" + this.roleIds.length + "项吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$http.get("/system/role/batchDelete?roleIds=" + this.roleIds).then(resp => {
            this.$message.success("删除成功");
            this.loadUser();
          }).catch(error => {
            this.$message.error("删除失败");
            console.error('删除请求失败:', error);
          });
        }).catch(() => {
          this.$message.warning("取消删除");
        });
      },
    // 删除单条数据
    handleDelete(row) {
      this.$confirm('确认删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get("/system/role/delete/" + row.roleId).then(resp => {
          this.$message.success("删除成功");
          this.getRoleList()// 列表重新查询
        }).catch(error => {
          this.$message.error("删除失败");
        });
      }).catch(() => {
        this.$message.warning("取消删除");
      });
    },
    // 分页pageSize变化时触发
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getRoleList()
    },
    // 点击上一页  下一页，跳转到哪一页面时触发
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getRoleList()
    },
    resetForm() {
      this.form = {
        roleId: undefined,
        roleName: '',
        roleCode: '',
        roleSort: 0,
        remark: '',
        status: '0'
      };
    },
    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        roleId: undefined,
        roleName: undefined,
        roleCode: undefined,
        remark: undefined,
        dateRange: []
      }
      this.getRoleList();
    },
    // 重置表单
    reset() {
      this.resetForm('form')
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleCode: undefined,
        roleSort: 0,
        remark: undefined,
        status: '0'
      }
      this.getRoleList();
    },

    // 打开添加的弹出层
    handleAdd() {
      this.title = '---添加角色---'
      this.open = true
      this.reset()
    },
    // 打开修改的弹出层并加载数据
    handleUpdate(row) {
      this.title = '---修改角色---'
      const roleId = row.roleId || this.ids
      this.open = true
      this.$http.get("/system/role/getByRoleId/" + roleId).then(res => {
        if (res.data.code === 200) {
          // this.$message.success("查询成功")
          this.form = res.data.data
        }
      })
    },
    // 增加修改确定
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 做添加
          if (this.form.roleId === undefined) {
            this.$http.post("/system/role/add_update_role", this.form).then(res => {
              this.$message.success('---添加成功---')
              this.getRoleList()// 列表重新查询
              this.open = false// 关闭弹出层
            })
          } else { // 做修改
            this.$http.post("/system/role/add_update_role", this.form).then(res => {
              this.$message.success('---修改成功---')
              this.getRoleList()// 列表重新查询
              this.open = false// 关闭弹出层
            })
          }
        }
      })
    },

    // 格式化状态
    statusFormatter(row) {
      let statusName = "未知";
      this.statusOptions.filter(item => {
        if (row.status === item.dictValue) {
          statusName = item.dictLabel;
        }
      })
      return statusName;
    },
    //加载状态
    loadStatus() {
      this.$http.get("/system/dict/data/type/sys_normal_disable").then(resp => {
        this.statusOptions = resp.data.data;
      })
    },
    // 搜索
    handleQuery() {
      this.getRoleList();
    },

  }
}

</script>
